//
//  LoginViewModel.swift
//  LoginForm
//
//  Created by work on 14/03/2018.
//  Copyright © 2018 work. All rights reserved.
//
import Foundation
import RxSwift

struct LoginViewModel {
    var username = Variable<String>("")
    var password = Variable<String>("")
    var verifyPassword = Variable<String>("")
    var email = Variable<String>("")
    
    var isValid: Observable<Bool> {
        return Observable.combineLatest(username.asObservable(), password.asObservable(),verifyPassword.asObservable(),email.asObservable()) {
            self.usernameValid(username: $0) && self.passwordValid(password: $1) && self.verifyPasswordValid(password1: $2, with: $1) && self.emailValid(email: $3)
        }
    }
    
    private func usernameValid(username:String) -> Bool {
        return username.count >= 3
    }
    
    private func passwordValid(password:String) -> Bool {
        return password.count >= 2
    }
    
    private func verifyPasswordValid(password1:String , with password2:String) -> Bool {
        return password1 == password2
    }
    
    private func emailValid(email:String) -> Bool {
        do{
            let pattern = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
            let regex: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            let matches = regex.matches(in: email, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, email.count))
            return matches.count > 0
        }
        catch{
            return false
        }
        
    }
    
}
